#include "Util.hpp"
#include "config.hpp"
#include "data.hpp"
#include "User.hpp"
#include "hot.hpp"
#include "service.hpp"
#include "daemon.hpp"

// cloud::DataManager *_data; // 方便hot.hpp里面的extern

std::unordered_map<std::string, std::shared_ptr<cloud::DataManager>> _Data;

void RunModule()
{
    // 第一次获取
    std::vector<cloud::User> _user;
    // 获取当前已经有的用户
    cloud::UserManager::GetInstance()->GetAll(_user);
    // 创建属于自己的data
    for (int i = 0; i < _user.size(); ++i)
    {
        _Data[_user[i]._Email] = std::shared_ptr<cloud::DataManager>(new cloud::DataManager(_user[i]._Email));
    }
    // 遍历,查看有没有增加用户
    while (1)
    {
        if (cloud::UserManager::GetInstance()->size() > _user.size())
        {
            // 已经赋值的位置
            int pos = _user.size();
            cloud::UserManager::GetInstance()->GetAll(_user);
            for (int i = pos; i < _user.size(); ++i)
            {
                _Data[_user[i]._Email] = std::shared_ptr<cloud::DataManager>(new cloud::DataManager(_user[i]._Email));
            }
        }
        sleep(1);
    }
}

int main()
{
    //守护进程
    //daemon();

    cloud::service server;
    cloud::hot hot;
    std::thread thread_userdata([&]
                                { RunModule(); });
    std::thread thread_service([&]
                               { server.RunModule(); });
    std::thread thread_host([&]
                            { hot.RunModule(); });

    thread_service.join();
    thread_service.join();
    thread_service.join();

    return 0;
}
